package com.fowo.api.syncAmazon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.entity.AmazonExchangeOrder;
import com.fowo.api.entity.TmpExchangeOrder;
import com.fowo.api.mapper.AmazonExchangeOrderMapper;
import com.fowo.api.mapper.TmpExchangeOrderMapper;
import com.fowo.api.syncAmazon.api.ExchangeOrderReportService;
import com.fowo.api.syncAmazon.mapper.AmazonTmpMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ExchangeOrderServiceImpl extends ServiceImpl<AmazonExchangeOrderMapper, AmazonExchangeOrder> {

    @Resource
    private TmpExchangeOrderMapper tmpExchangeOrderMapper;
    @Resource
    private ExchangeOrderReportService orderReportService;
    @Resource
    private AmazonTmpMapper amazonTmpMapper;

    /**
     * 同步换货订单
     * @throws Exception
     */
    public void syncExchangeOrder() throws Exception {
        //清空临时表
        amazonTmpMapper.deleteAllExchangeOrder();
        //拉取数据到临时表
        orderReportService.getTmpExchangeOrder();

        List<TmpExchangeOrder> exchangeOrders = tmpExchangeOrderMapper.selectList(new QueryWrapper<TmpExchangeOrder>().eq("del_flag", 0));
        List<AmazonExchangeOrder> insertList = new ArrayList<>();
        if(exchangeOrders != null && exchangeOrders.size() > 0){
            for (TmpExchangeOrder exchangeOrder:exchangeOrders) {
                QueryWrapper<AmazonExchangeOrder> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("del_flag",0);
                orderWrapper.eq("replacement_amazon_order_id",exchangeOrder.getReplacementAmazonOrderId());
                int count = (int) this.count(orderWrapper);
                if(count > 0){
                    continue;
                }
                AmazonExchangeOrder order = new AmazonExchangeOrder();
                BeanUtils.copyProperties(exchangeOrder,order);
                order.setId(null);
                order.setCreateTime(new Date());
                insertList.add(order);
            }
            List<List<AmazonExchangeOrder>> partition = Lists.partition(insertList, 200);
            for (List<AmazonExchangeOrder> amazonExchangeOrders:partition) {
                this.saveBatch(amazonExchangeOrders);
            }
        }
    }

}
